<?php
/*************************************************************************
 * BASE MODEL
 *************************************************************************/
require_once dirname(realpath(__FILE__)).'./../config/config.inc.php';

abstract class Model {
  /**
   * Properties definition
   * @var 
   * $properties = array {
   * 							 	array('name'=>'name', 'required'=>true),
   * 								array('name'=>'name2', 'required'=>false)
   * 							 }
   */
  protected $properties = array();
  protected $Db;
  protected $records;

#----------------------------------------------------------------------------------
  /**
   * Constructor
   * @param int $id id of object
   * @param array List of property
   */
  protected function __construct($id = '', $tableName, $properties) {
    try {
      $this->Db = new Db();
      
      if ($id != '') {
        $query = sprintf("SELECT * FROM %s WHERE id='%d' LIMIT 1",
                          mysql_escape_string($tableName),
                          mysql_escape_string(id));
        
        $this->records = $Db->select($query);
      }
    } catch (Exception $e) {
      throw new Exception($e->getMessage());
    } 
  }
  
#----------------------------------------------------------------------------------
  /**
   * Magic function for get property
   */
  public function __call($methodName, $args) {
      $action = substr($methodName, 0, 3);
     	$tmp = substr($methodName, 3);
     	$firstChar = substr($tmp, 0, 1);
     	$otherChars = substr($tmp, 1); 
     	
     	$fieldName = strtolower($firstChar).$otherChars;

     	try {
     	  $propertyExists = false;
     	  foreach($this->properties as $property) {
     	    if ($property['name'] == $$propertyName) $propertyExists = true;
     	  }

     	  if (!$propertyExists) throw new Exception('File : '.__FILE__.'<br />Line : '.__LINE__."<br />Error : Method $methodName does not exist.");
     	
     	} catch (Exception $e) {
     	  echo $e->getMessage();
     	}
    
     	# if via fetch object then return directly the value
     	if ($this->isViaFetchObject) {
     	  return $this->$fieldName;
     	  
     	# if not via fet object then request to Db
     	} else {
     	  try {
        	if($action == 'get'){
            return $this->preparedData[$fieldName];
        	}elseif($action == 'set'){
        		$query = sprintf('UPDATE advertisement SET %s=\'%s\' WHERE id=%d LIMIT 1',
        		                  mysql_escape_string($fieldName),
    													mysql_escape_string($args[0]),
    											  	mysql_escape_string($this->advertisementId));
        	  $result = $this->Db->update($query);
        	  return $result;
        	}
  			}	catch (Exception $e) {
  				echo $e->getMessage();
  			}
     	}
  }
}